package juc.demo;

public class ThreadTest {

    public static void main(String[] args) {

        new ThreadTest().init();

    }


    void init()

    {

        final Business business = new Business();

        new Thread(new Runnable() {

            @Override
            public void run() {

                for (int i = 1; i <= 50; i++) {
                    business.subThread(i);
                }
            }
        }

                , "子线程").start();


        for (int i = 1; i <= 50; i++)

        {

            business.mainThread(i);

        }

    }


    private class Business

    {

        /**
         * 这里相当于定义了控制该谁执行的一个信号灯
         */
        boolean bShouldSub = true;

        private synchronized void mainThread(int i)

        {

            while (bShouldSub) {

                try {

                    this.wait();

                } catch (InterruptedException e) {

                    e.printStackTrace();

                }
            }

            for (int j = 1; j <= 5; j++)

            {

                System.out.println(Thread.currentThread().getName() + ":第" + i + "轮," + "j=" + j);

            }

            bShouldSub = true;

            this.notify();


        }


        private synchronized void subThread(int i)

        {

            while (!bShouldSub) {

                try {

                    this.wait();

                } catch (InterruptedException e) {

                    e.printStackTrace();

                }
            }


            for (int j = 1; j <= 10; j++) {

                System.out.println(Thread.currentThread().getName() + ":第" + i + "轮," + "j=" + j);
            }

            bShouldSub = false;
            this.notify();

        }

    }

}
